package common.tree;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class BinaryTree {
    private class TreeNode {
        public int value;
        public TreeNode left;
        public TreeNode right;

    }
    private TreeNode root;

    public static void main(String[] args) {
        BinaryTree binaryTree = new BinaryTree();
        binaryTree.add(10);
        binaryTree.add(9);
        binaryTree.add(5);
        binaryTree.add(12);
        binaryTree.add(20);
        binaryTree.add(17);
        binaryTree.add(31);
        binaryTree.add(28);

        System.out.println(Arrays.toString(binaryTree.reverse_evens()));
    }


    public int[] reverse_evens() {
        List<Integer> list = new ArrayList<>();
        postOrder(root, list);
        int[] array = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            array[i] = list.get(i);
        }
        return array;
    }

    private void postOrder(TreeNode node, List<Integer> list) {
        if (node == null) {
            return;
        }
        postOrder(node.right, list);
        if (node.value % 2 == 0) {
            list.add(node.value);
        }
        postOrder(node.left, list);
    }

    public boolean add(int value) {
        TreeNode newNode = new TreeNode();
        newNode.value = value;
        if (root == null) {
            root = newNode;
            return true;
        }

        TreeNode node = root;
        while (true) {
            if (node.value == value) {
                return false;
            }

            if (node.value < value) {
                if (node.right == null) {
                    node.right = newNode;
                    return true;
                } else {
                    node = node.right;
                }
            } else {
                if (node.left == null) {
                    node.left = newNode;
                    return true;
                } else {
                    node = node.left;
                }
            }
        }
    }
}